<template>
  <div class="app-container">
    <h2 style="text-align: center">发布新课程</h2>

    <el-steps
      :active="1"
      process-status="wait"
      align-center
      style="margin-bottom: 40px"
    >
      <el-step title="填写课程基本信息" />
      <el-step title="创建课程大纲" />
      <el-step title="最终发布" />
    </el-steps>

    <el-form label-width="120px">
      <el-form-item label="课程标题">
        <el-input
          :aria-required="true"
          v-model="courseInfo.title"
          placeholder=" 示例：java20天从入门到入土"
        />
      </el-form-item>

      <el-form-item label="课程分类">
        <!-- 一级分类 -->
        <el-select
          v-model="courseInfo.subjectParentId"
          placeholder="一级分类"
          @change="change"
        >
          <el-option
            v-for="subject in subjectOneList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"
          />
        </el-select>

        <!-- 二级分类 -->
        <el-select v-model="courseInfo.subjectId" placeholder="二级分类">
          <el-option
            v-for="subject in subjectTwoList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"
          />
        </el-select>
      </el-form-item>

      <!-- 课程讲师 -->
      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number
          :min="0"
          v-model="courseInfo.lessonNum"
          controls-position="right"
          placeholder="请填写课程的总课时数"
        />
      </el-form-item>

      <!-- 课程简介-->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description" />
      </el-form-item>

      <!-- 课程封面-->
      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API + '/eduoss/fileoss'"
          class="avatar-uploader"
        >
          <img :src="courseInfo.cover" />
        </el-upload>
      </el-form-item>

      <!-- 课程价格 -->
      <el-form-item label="课程价格">
        <el-input-number
          :min="0"
          v-model="courseInfo.price"
          controls-position="right"
          placeholder="免费课程请设置为0元"
        />
        元
      </el-form-item>

      <el-form-item>
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate"
          >保存并下一步</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import course from "@/api/course/course";
import subject from "@/api/subject/subject";
import Tinymce from "@/components/Tinymce";

export default {
  components: { Tinymce }, //声明富文本组件
  data() {
    return {
      saveBtnDisabled: false, // 保存按钮是否禁用
      courseInfo: {
        title: "",
        subjectId: "", //二级分类id
        subjectParentId: "", //一级分类id
        teacherId: "",
        lessonNum: 0,
        description: "",
        cover:
          "https://edu-young160.oss-cn-beijing.aliyuncs.com/defaultCover.jpg",
        price: 0,
      },
      BASE_API: process.env.BASE_API, //接口api地址
      teacherList: {}, //讲师列表
      subjectOneList: {}, //一级分类列表
      subjectTwoList: {},
      courseId: ''
    };
  },

  created() {
    //取id，回显表单，判断添加操作还是修改操作
    if(this.$route.params && this.$route.params.id) {
        this.courseId = this.$route.params.id
        this.backToInfo()
        this.getAllTeacher()
      }else {
        //修复回显数据页面再次点击添加课程路由，回显数据仍然存在的问题
        this.courseInfo = {
        title: "",
        subjectId: "", //二级分类id
        subjectParentId: "", //一级分类id
        teacherId: "",
        lessonNum: 0,
        description: "",
        cover:
          "https://edu-young160.oss-cn-beijing.aliyuncs.com/defaultCover.jpg",
        price: 0,
      }
        //初始化选择讲师列表的下拉菜单
        this.getAllTeacher()
        //初始化课程分类列表的下拉菜单
        this.getOneSubject()
      }
  },

  methods: {
    //点击上一步，回显到info界面
    backToInfo(){
      course.getCourseInfoId(this.courseId)
        .then((res) => {
          //在courseInfo中，包含一级和二级分类id
          this.courseInfo = res.data.courseInfoVo
          //1 查询所有分类，包含一级和二级
          subject.getSubjectList()
            .then((res) => {
              //2 获取所有一级分类
              this.subjectOneList = res.data.list
                this.subjectOneList.forEach(one => {
                  //比较当前courseInfo里面一级分类id和所有一级分类id
                  if(one.id === this.courseInfo.subjectParentId){
                    //获取一级分类id所有的二级分类
                    this.subjectTwoList = one.children
                  }
                })
            })
        })
    },

    //上传成功调用方法
    handleAvatarSuccess(res, file) {
      this.courseInfo.cover = res.data.url;
    },
    //上传之前调用方法
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    //点击选择一级分类后触发change事件获取二级分类
    change(value) {
      subject.getSubjectList().then((res) => {
        //one:遍历所有一级分类得到
        this.subjectOneList.forEach((one) => {
          //遍历所有一级分类的子元素
          console.log(one.children);
          if (value === one.id) {
            this.subjectTwoList = one.children;
          }
        });
        this.courseInfo.subjectId = "";
      });
    },
    //查询所有一级分类
    getOneSubject() {
      subject.getSubjectList().then((res) => {
        this.subjectOneList = res.data.list;
      });
    },
    
    //添加课程信息
    addCourse() {
      course.addCourseInfo(this.courseInfo).then((res) => {
          this.$message({
            type: "success",
            message: "添加课程信息成功",
          });
        
        //跳转到第二步
        this.$router.push({ path: "/course/chapter/" + res.data.courseId });
      });
    },

    //修改课程
    updateCourse() {
      course.updateCourseInfoId(this.courseInfo)
        .then(() => {
          //提示信息
          this.$message({
            type: "success",
            message: "修改课程信息成功",
          });

          //跳转到第二步
          this.$router.push({ path: "/course/chapter/" + this.courseId });
        })
    },

    saveOrUpdate(){
      //通过地址栏是否有id判断是添加方法还是修改方法
      if(this.$route.params && this.$route.params.id) {
        //有值且id存在
        this.updateCourse()
      }else {
        //添加
        this.addCourse()
      }

    },

    //查询所有讲师
    getAllTeacher() {
      course.getListTeacher().then((res) => {
        this.teacherList = res.data.items;
      });
    },
  },
};
</script>
<style scoped>
.tinymce-container {
  line-height: 29px;
}
</style>